package com.nhatviet.webservice.activities.flickr;

import java.io.InputStream;
import java.io.InputStreamReader;

import com.nhatviet.webservice.AppMain;
import com.nhatviet.webservice.R;
import com.nhatviet.webservice.helpers.FlickrService;
import com.nhatviet.webservice.helpers.OpenHttpConnection;
import com.nhatviet.webservice.helpers.XMLParserHandler;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class FlickrSearchActivity extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.flickr_search);

		Button buttonSearch = (Button) findViewById(R.id.button_search);
		final EditText textLatitude = (EditText) findViewById(R.id.text_latitude);
		final EditText textLongitude = (EditText) findViewById(R.id.text_longitude);
		final EditText textRadius = (EditText) findViewById(R.id.text_radius);

		buttonSearch.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v)
			{
				String latituteStr = textLatitude.getText().toString();
				String longitudeStr = textLongitude.getText().toString();
				String radiusStr = textRadius.getText().toString();

				String urlStr = FlickrService.getURL("flickr.photos.search", "10f1ed3933b9ca4f0301777402f4a471", latituteStr, longitudeStr, radiusStr, FlickrService.UNIT_KILOMETER, FlickrService.FORMAT_XML);
				try
				{
					/* Get the stream */
					InputStream inputStream = new OpenHttpConnection().get(urlStr);
					if (inputStream == null)
					{
						AppMain.alert(FlickrSearchActivity.this, "Network error!", "Please check the network!");
					}
					else
					{
						InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
						/* Get the string return */
						int charRead = 0;
						String resultStr = "";
						char[] charBuffer = new char[2000];
						while ((charRead = inputStreamReader.read(charBuffer)) > 0)
						{
							resultStr += String.valueOf(charBuffer, 0, charRead);
							charBuffer = new char[2000];
						}
						Log.d("Debug", resultStr);
						/* parse XML with the first XMLParserHandler */
						if(AppMain.xmlParserHandlerList != null && AppMain.xmlParserHandlerList.size() > 0)
							AppMain.xmlParserHandlerList.clear();
						AppMain.xmlParserHandlerList.add(new XMLParserHandler());
						AppMain.readXMLData(AppMain.xmlParserHandlerList.get(0), resultStr);

						Intent intent = new Intent(FlickrSearchActivity.this, FlickrResultsActivity.class);
						startActivity(intent);
					}

				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}
}
